<script setup lang="ts">
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import { useIcon } from '@/hooks/web/useIcon'
import { Table } from '@/components/Table'
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElSpace,
  ElDivider,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElCheckbox,
  ElTabs,
  ElTabPane, ElUpload, ElMessage
} from 'element-plus'
import { reactive, ref, h, watch, unref } from 'vue'
import { useTable } from "@/hooks/web/useTable";
import { DataData } from "@/api/manage/data/types";
import { getDataListApi, saveOrUpdate, delDataApi, startDataApi, stopDataApi, getDataDetailApi, dataAuthApi, dataLicenseApi } from "@/api/manage/data/index";
import { Pagination, TableColumn } from "@/types/table";
import Edit from "./edit.vue";
import { Dialog } from '@/components/Dialog'
import { FormSchema } from "@/types/form";
import { useValidator } from "@/hooks/web/useValidator";
import EditPermit from "@/views/manage/data/editPermit.vue";
import EditAuth from "@/views/manage/data/editAuth.vue";
import { downloadStatic } from "@/api/common/index"

import { OrgData } from "@/api/org/types";
import { getSelectOrgListApi } from "@/api/org/index";
import { PATH_URL } from '@/config/axios/service'
//秘文端管理
const { required } = useValidator()

const queryModel = reactive<Recordable>({
  company_id: '',
  service_id: '',
  service_name: ''
})
const stateOptions = [
  { label: "运行中", value: 1101 },
  { label: "已停止", value: 1102 },
  { label: "已禁用", value: 1103 },
  { label: "未授权", value: 1104 },
  { label: "空间不足", value: 1105 },
  { label: "未知", value: 1106 }
];
const columns = reactive<TableColumn[]>([
  {
    field: 'state',
    label: '状态',
    visible: true,
    className: ''
  }, {
    field: 'service_id',
    label: '秘文端ID',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'service_name',
    label: '秘文端名称',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'alias',
    label: '秘文端别名',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'company_id',
    label: '组织',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'domain',
    label: '域名',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'inner_ip',
    label: '内网IP',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'inner_port',
    label: '内网端口',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'outer_ip',
    label: '外网IP',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'outer_port',
    label: '外网端口',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'storage1',
    label: '剩余/仓库总空间',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'storage2',
    label: '剩余/磁盘总空间',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'action',
    label: '操作',
    visible: true,
    className: '',
    fixed: "right",
    width: 320
  }
])

const { register, tableObject, methods } = useTable<DataData>({
  getListApi: getDataListApi,
  delListApi: delDataApi,
  response: {
    list: 'list',
    total: 'total'
  }
})
const paginationObj = ref<Pagination>()
watch(() => tableObject.total,
  (val) => {
    if (val > 0) {
      paginationObj.value = {
        total: tableObject.total
      }
    } else {
      paginationObj.value = undefined
    }
  })
const { getList, setSearchParams } = methods
getList()

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' }),
  deleteIcon: useIcon({ icon: 'ep:delete' })
}
const spacer = h(ElDivider, { direction: 'vertical' })

const handleQuery = () => {
  let queryParams: Recordable = {} as any
  if (queryModel.column) {
    queryParams[queryModel.column] = queryModel.val
  }
  setSearchParams({ queryParams })
}

const selectedCount = ref(0)
const multipleSelection = ref<DataData[]>([])
const handleSelectionChange = (val: DataData[]) => {
  multipleSelection.value = val
  selectedCount.value = val?.length || 0
}

const handleVisibleChange = (item) => {
  item.className = item.visible ? '' : 'hidden'
}

const dialogVisible = ref(false);
const dialogTitle = ref("");
const actionType = ref("");
const loading = ref(false)
const delLoading = ref(false)
const editRef = ref<ComponentRef<typeof Edit>>()
const save = async () => {
  const Data = unref(editRef)
  await Data?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await Data?.getFormData()) as DataData
      const isUpdate = actionType.value == 'edit';
      const res = await saveOrUpdate(data, isUpdate)
        .catch(() => {
        })
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.page_index = 1
        getList()
      }
    }
  })
}
const handleAdd = () => {
  tableObject.currentRow = null
  actionType.value = ''
  dialogTitle.value = '新增秘文端'
  dialogVisible.value = true
}

const handleEnableButton = (row: DataData) => {
  const id = row.service_id;
  startDataApi(id).then(res => {
    ElMessage.success(res.msg);
  }).catch(() => {
    ElMessage.error("异常，请联系管理员！");
  });
}
const handlePauseButton = (row: DataData) => {
  const id = row.service_id;
  stopDataApi(id).then(res => {
    ElMessage.success(res.msg);
  }).catch(() => {
    ElMessage.error("异常，请联系管理员！");
  });
}

const handleEditButton = (row: DataData) => {
  getDataDetailApi(row.service_id).then(res => {
    tableObject.currentRow = res.data
    actionType.value = 'edit'
    dialogTitle.value = '编辑秘文端'
    dialogVisible.value = true
  });
}
const handleDeleteButton = async (row: DataData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delListByObj, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delListByObj(
    multiple ? selections : [row] as DataData[],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const formSchema = reactive<FormSchema[]>([
  {
    field: 'company_id',
    label: '组织ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'service_id',
    label: '秘文端ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'domain',
    label: '秘文端登录账号',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'alias',
    label: '秘文端别名',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'key',
    label: '设置密码',
    component: 'InputPassword',
    formItemProps: {
      rules: [required(), { min: 8, max: 20, message: '密码长度8到20位', trigger: 'blur' }]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'total_space',
    label: '设置总空间',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 18
    }
  },
  {
    field: 'occupancy_space',
    label: '占用空间',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 18
    }
  },
  {
    field: 'snapshot_space',
    label: '快照上限',
    component: 'Input',
    componentProps: {
      slots: {
        append: true
      }
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 18
    }
  },
  {
    field: 'inner_ip',
    label: '内网地址',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'inner_port',
    label: '内网端口',
    component: 'InputNumber',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'outer_ip',
    label: '外网地址',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'outer_port',
    label: '外网端口',
    component: 'InputNumber',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_license',
    label: '许可证',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  }
]);
const handleReset = () => {
  const edit = unref(editRef)
  edit?.elFormRef?.resetFields()
}

const activeTabName = ref("second")

const editPermitRef = ref<ComponentRef<typeof EditPermit>>()
const permitFormSchema = reactive<FormSchema[]>([
  {
    field: 'ssdevice_license',
    label: '许可证',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_lsn',
    label: '机器码',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_license_state',
    label: '许可证状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '许可证为空',
          value: 0
        },
        {
          label: '许可证机器码已配对',
          value: 1
        },
        {
          label: '数据端提交许可证无效',
          value: 2
        }
      ],
      disabled: true
    },
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'license_deadline',
    label: '许可证有效期',
    component: 'Input',
    componentProps: {
      disabled: true
    },
    formItemProps: {
      required: false,
    }, colProps: {
      span: 24
    }
  }
])

const handleEditPermitButton = async () => {
  const Data = unref(editPermitRef)
  await Data?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await Data?.getFormData()) as DataData

      dataLicenseApi(data).then(res => {
        ElMessage.success(res.msg);
        dialogVisible.value = false
        tableObject.page_index = 1
        getList()
      }).catch(() => {
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

const dialogAuthVisible = ref(false)
const editAuthRef = ref<ComponentRef<typeof EditAuth>>()
const handleAuthReset = () => {
  const edit = unref(editAuthRef)
  edit?.elFormRef?.resetFields()
}

const currentAuthRow = ref<DataData>()
const authFormSchema = reactive<FormSchema[]>([
  {
    field: 'company_id',
    label: '组织ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'service_id',
    label: '数据端ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  }
  , {
    field: 'ssdevice_license',
    label: '许可证',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_lsn',
    label: '机器码',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  }
])
const saveAuth = async () => {
  const Data = unref(editAuthRef)
  await Data?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await Data?.getFormData()) as DataData
      dataAuthApi(data).then(res => {
        ElMessage.success(res.msg);
      }).catch(() => {
      }).finally(() => {
        loading.value = false
      })
    }
  })
}
const handleAuthButton = (row: DataData) => {
  console.log(row)
  const id = row.service_id;
  getDataDetailApi(id).then(res => {
    currentAuthRow.value = res.data
    dialogAuthVisible.value = true
  })
}
const downloadTemplate = () => {
  const fileName = "data.xlsx";
  downloadStatic(`/static/excel/${fileName}`, fileName);
}

const companyList = ref([] as OrgData[]);

getSelectOrgListApi().then(res => {
  companyList.value = res.data
})
</script>

<template>
  <ContentWrapNoHeaderLine title="秘文端管理">
    <div class="flex justify-between">
      <el-form :inline="true" ref="queryFormRef" :model="queryModel">
        <el-form-item>
          <el-space direction="horizontal" :size="0">
            <el-select v-model="queryModel.company_id" placeholder="组织机构">
              <el-option v-for="item in companyList" :label="`${item.name}`" :key="item.companyId"
                :value="`${item.companyId}`" />
            </el-select>
            <el-input v-model="queryModel.service_id" placeholder="秘文端ID" />
            <el-input v-model="queryModel.service_name" placeholder="秘文端别名">
              <template #append>
                <el-button class="query-button" type="primary" @click="handleQuery">查询</el-button>
              </template>
            </el-input>
          </el-space>
        </el-form-item>
        <el-form-item>
          <!-- <el-button>查看监控</el-button> -->
          <el-button @click="downloadTemplate">模板下载</el-button>
        </el-form-item>
      </el-form>
      <el-button :icon="icons.plusIcon" type="primary" @click="handleAdd">新增秘文端</el-button>
    </div>
    <div class="rounded bg-gray-100 w-full flex justify-between px-1.5 py-2 mb-3.5">
      <el-space :size="10" :spacer="spacer">
        <div>已批量选择<span class="mx-1 text-[var(--el-color-primary)]">{{ selectedCount }}</span>条事项</div>
        <div class="flex upload-toolbar">
          <el-button :icon="icons.deleteIcon" link @click="handleDeleteButton(null, true)">批量删除</el-button>
          <ElDivider direction="vertical" style="margin-top: auto;" />
          <el-upload :action="`${PATH_URL}/data/imp`" :limit="1">
            <el-button :icon="icons.plusIcon" link>批量创建</el-button>
          </el-upload>
        </div>
      </el-space>
      <el-space :size="10">
        <el-dropdown trigger="click" :hide-on-click="false">
          <span class="el-dropdown-link">
            <Icon icon="icon-park-outline:config" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <div class="flex flex-col p-2">
              <template v-for="column in columns">
                <el-checkbox
                 v-if="column.field !== 'action'" v-model="column.visible" :label="column.label"
                  :key="column.field" size="small" @change="handleVisibleChange(column)" />
              </template>
            </div>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <Icon icon="bi:download" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出到Csv</el-dropdown-item>
              <el-dropdown-item>导出到Excle</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <Icon icon="bi:printer" class="cursor-pointer " />
      </el-space>
    </div>
    <div class="">
      <Table 
      border v-model:pageSize="tableObject.page_size" v-model:currentPage="tableObject.page_index"
        :columns="columns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="paginationObj"
        @register="register" @select="handleSelectionChange" @select-all="handleSelectionChange">
        <template #state="{ row }">
          <template v-for="o in stateOptions">
            <template v-if="o.value === row.state">
              {{ o.label }}
            </template>
          </template>
        </template>
        <template #action="{ row }">
          <el-space :size="6" :spacer="spacer">
            <ElButton type="primary" link @click="handleEnableButton(row)">
              启用
            </ElButton>
            <ElButton type="primary" link @click="handlePauseButton(row)">
              暂停
            </ElButton>
            <ElButton type="primary" link @click="handleAuthButton(row)">
              授权
            </ElButton>
            <ElButton type="primary" link @click="handleEditButton(row)">
              编辑
            </ElButton>
            <ElButton type="primary" link @click="handleDeleteButton(row, false)">
              删除
            </ElButton>
          </el-space>
        </template>
      </Table>
    </div>
  </ContentWrapNoHeaderLine>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="470" :max-height="'100%'" top="4vh">
    <el-tabs v-if="actionType === 'edit'" v-model="activeTabName">
      <el-tab-pane label="基础信息" name="first">
        <Edit ref="editRef" :form-schema="formSchema" :current-row="tableObject.currentRow" />
      </el-tab-pane>
      <el-tab-pane label="许可证设置" name="second">
        <EditPermit ref="editPermitRef" :form-schema="permitFormSchema" :current-row="tableObject.currentRow" />
      </el-tab-pane>
    </el-tabs>

    <Edit v-else ref="editRef" :form-schema="formSchema" :current-row="tableObject.currentRow" />

    <template v-if="activeTabName === 'first'" #footer>
      <ElButton @click="handleReset">重置</ElButton>
      <ElButton type="primary" :loading="loading" @click="save">
        提交
      </ElButton>
    </template>
    <template v-else #footer>
      <ElButton type="primary" :loading="loading" @click="handleEditPermitButton">
        修改许可证
      </ElButton>
    </template>
  </Dialog>
  <Dialog v-model="dialogAuthVisible" title="授权" :width="470" :max-height="'100%'">
    <Edit ref="editAuthRef" :form-schema="authFormSchema" :current-row="currentAuthRow" />
    <template #footer>
      <ElButton @click="handleAuthReset">重置</ElButton>
      <ElButton type="primary" :loading="loading" @click="saveAuth">
        提交
      </ElButton>
    </template>
  </Dialog>
</template>
<style scoped>
.upload-toolbar>div {
  display: flex;
}
</style>